package com.ts.manage.cms.client.mq;

import com.alibaba.fastjson.JSON;
import com.ts.framework.domain.cms.CmsPage;
import com.ts.framework.domain.cms.response.CmsCode;
import com.ts.framework.exception.ExceptionCast;
import com.ts.manage.cms.client.dao.CmsPageRepository;
import com.ts.manage.cms.client.service.CmsPagePostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * 接收页面发布消息
 */
@Component
@Slf4j
public class CmsPagePostConsumer {
    @Autowired
    private CmsPagePostService cmsPagePostService;
    @Autowired
    private CmsPageRepository cmsPageRepository;
    @RabbitListener(queues = {"${ts.mq.queue}"})
    public void postCmsPage(String msg){
        //解析消息
        Map map = JSON.parseObject(msg, Map.class);
        log.error("receive post cms page:{}",map.toString());
        //获取页面id
        String pageId = (String) map.get("pageId");
        //查询页面信息
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        if (!optional.isPresent()){
            ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
        }

        //将页面保存到服务器物理路径
        cmsPagePostService.savePage2Location(pageId);
    }

}
